<script setup lang="ts">
import { find } from "lodash";
import { useMap } from "@/views/pipe-network/components/Map/index.vue";
import { ref } from "vue";
import { LPolyline, LCircle, LMarker } from "@vue-leaflet/vue-leaflet";
import { useMapStore } from "@/store";
import { MAP_ACTION } from "@/views/pipe-network/constants";
import { deletePolyline, queryPolylines } from "@/api/pipe";
import { getAssetsFile } from "@/utils/map";
import { useLocalStore } from "@/views/layer/gismap/store";
import LineAPI from "@/api/LineAPI";
const { L }: any = window;
const props = defineProps({
  deviceCategoryList: Array<any>,
  tableLine: Array<any>,
});

const tableLineData = ref([]);
const dialogVisible = ref<boolean | number>(false);
const polylineListRef = ref([]);
const circleMarkerPositionRef = ref();
const activePolylineRef = ref();
const map = useMap();
const mapStore = useMapStore();
const { mapAction } = storeToRefs(mapStore);
const localStore = useLocalStore();
const { visibleLineClassIds } = storeToRefs(localStore);
let timer;
const onClick = (e) => {
  const isConnectionTwoPointsAction =
    mapAction.value === MAP_ACTION.ADD_POINT_ONLINE;
  const isPointDevideLineAction =
    mapAction.value === MAP_ACTION.DEVIDE_LINE_WITH_POINT;
  const isMoveAction = mapAction.value === MAP_ACTION.MOVE;
  const isModifyInfoAction = mapAction.value === MAP_ACTION.EDIT;
  if (isConnectionTwoPointsAction) {
    mapStore.setAddedPipePointOnLine(e.latlng);
  }
  if (isPointDevideLineAction) {
    const latlngs = e.target.getLatLngs();
    mapStore.setPointDevideLine({
      point: e.latlng,
      lines: [
        [latlngs[0], e.latlng],
        [e.latlng, latlngs[1]],
      ],
    });
  }
  if (isMoveAction) {
    map.on("movestart", onMoveStart).on("moveend", onMoveEnd);
  }
  if (isModifyInfoAction) {
    const { lineId } = e.target.options.attribution;
    const obj = polylineListRef.value.find(
      (item: any) => item.lineId === lineId
    );
    if (obj) {
      mapStore.setEditingPipeLine(obj);
    }
  }
};
const onHover = (e) => {
  const isConnectionTwoPointsAction =
    mapAction.value === MAP_ACTION.ADD_POINT_ONLINE;
  if (isConnectionTwoPointsAction) {
    circleMarkerPositionRef.value = e.latlng;
    activePolylineRef.value = e.target.getLatLngs();
    timer && clearTimeout(timer);
  }
};
const onUnHover = () => {
  const isConnectionTwoPointsAction =
    mapAction.value === MAP_ACTION.ADD_POINT_ONLINE;
  if (isConnectionTwoPointsAction) {
    timer = setTimeout(() => {
      activePolylineRef.value = null;
      circleMarkerPositionRef.value = null;
      timer = null;
    }, 2000);
  }
};
const getWeight = (lineId) => {
  if (!activePolylineRef.value) {
    return 4;
  } else {
    return 4;
  }
};
const onMoveStart = (e) => {};
const onMoveEnd = (e) => {};
const getColor = (classId: string) => {
  // debugger;
  const lineCategoryList = props.deviceCategoryList?.line;
  if (lineCategoryList) {
    const obj = lineCategoryList.find((item: any) => item.classId === classId);
    if (obj) {
      const { image } = obj;
      return image;
    }
  }
};

const getAllLines = () =>
  LineAPI.api_query({ pageSize: 100000, pageIndex: 1 }).then(
    ({ data, errors, succeeded }) => {
      if (succeeded && Array.isArray(data?.items)) {
        let dataArr = [];
        dataArr = data.items.map((item: any) => {
          if (item.endPositionId) {
            let tempArr = [];
            if (item.jsonLine.length) {
              JSON.parse(item.jsonLine).coordinates.forEach((ele, eleIndex) => {
                tempArr.push([ele[1], ele[0]]);
              });
            }
            item.checked = true;
            return {
              ...item,
              startPoint: [tempArr[0][0], tempArr[0][1]],
              coordinates: tempArr,
            };
          }
        });

        dataArr.forEach((item) => {
          if (item) {
            polylineListRef.value.push(item);
          }
        });

        // data.items.map((item: any) => {
        //   let tempArr = [];
        //   if (item.jsonLine.length) {
        //     JSON.parse(item.jsonLine).coordinates.forEach((ele, eleIndex) => {
        //       tempArr.push([ele[1], ele[0]]);
        //     });
        //   }
        //   item.checked = true;
        //   return {
        //     ...item,
        //     startPoint: [tempArr[0][0], tempArr[0][1]],
        //     coordinates: tempArr,
        //   };
        // });

        // polylineListRef.value = data.items
        //   .filter((item: any) => item.jsonGeom)
        //   .map((item: any) => {
        //     const { coordinates } = JSON.parse(item.jsonGeom);
        //     const [lng, lat] = coordinates[0];
        //     item.checked = true;
        //     return {
        //       ...item,
        //       coordinates: coordinates.map((item: any) => [item[1], item[0]]),
        //       startPoint: [lat, lng],
        //       color: getColor(item.classId),
        //     };
        //   });
      }
    }
  );
onMounted(() => getAllLines());
onUnmounted(() => {
  map && map.off("movestart", onMoveStart).off("moveend", onMoveEnd);
});
watchEffect(() => {
  tableLineData.value = props.tableLine;

  polylineListRef.value.forEach((item, index) => {
    if (
      !find(tableLineData.value, {
        inspLineId: item.inspLineId,
      })
    ) {
      polylineListRef.value[index].checked = false;
    } else {
      let isChecked = find(tableLineData.value, {
        inspLineId: item.inspLineId,
      }).checked;
      polylineListRef.value[index].checked = isChecked;
    }
  });
  // if (Array.isArray(visibleLineClassIds.value)) {
  //   polylineListRef.value.forEach((item: any) => {
  //     item.visible = visibleLineClassIds.value.includes(item.classId);
  //   });
  // } else {
  //   polylineListRef.value.forEach((item: any) => {
  //     item.visible = true;
  //   });
  // }
});
</script>

<template v-if="positionRef">
  <LPolyline
    :key="lineId"
    v-for="{ coordinates, lineId, checked } in polylineListRef.filter(
      (item: any) => item.visible !== false
    )"
    :lat-lngs="coordinates"
    :weight="getWeight(lineId)"
    :attribution="String(lineId)"
    :color="color"
    :visible="checked"
    @click="onClick"
    @mouseover="onHover"
    @mouseout="onUnHover"
  />
  <LCircle
    v-if="circleMarkerPositionRef"
    :lat-lng="circleMarkerPositionRef"
    color="purple"
    :radius="30"
    weight="10"
    @click="onClick"
  />
  <template v-if="mapAction === MAP_ACTION.ADD_PIPELINE">
    <LCircle
      v-for="{ startPoint, lineId } in polylineListRef"
      :key="lineId"
      :lat-lng="startPoint"
      :radius="20"
      color="red"
      fill-color="white"
      :fillOpacity="0.3"
      :pacity="0.3"
      @click="
        (e: any) =>
          mapStore.setStartPointInfo({
            original: e.target.getLatLng(),
            latlng: e.latlng,
          })
      "
      @mouseover="
        (e: any) => {
          e.target.getElement().style.fillOpacity = 1;
          e.target.getElement().style.opacity = 1;
        }
      "
      @mouseout="
        (e: any) => {
          e.target.getElement().style.fillOpacity = 0.3;
          e.target.getElement().style.opacity = 0.3;
        }
      "
    />
  </template>
</template>

<style scoped lang="scss"></style>
